﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.IO;

namespace VersionBuilder
{
	public class IncrementVersion : Task
	{
		private List<ITaskItem> generatedCompiles = new List<ITaskItem>();

		[Required]
		public ITaskItem[] VersionFiles { get; set; }

		public ITaskItem IncrementMajor { get; set; }
		public ITaskItem IncrementMinor { get; set; }
		public ITaskItem IncrementBuild { get; set; }
		public ITaskItem IncrementRevision { get; set; }

		[Output]
		public ITaskItem Value { get; set; }

		public override bool Execute()
		{
			if (this.VersionFiles.Length != 1)
			{
				this.Log.LogError("Must have exactly 1 VersionInfo file.");
				return false;
			}

			var versionFile = this.VersionFiles[0];
			var versionFileName = versionFile.ItemSpec;
			var versionString = File.ReadAllText(versionFileName);
			var version = default(Version);
			if (!Version.TryParse(versionString, out version))
			{
				this.Log.LogError("Unable to parse VersionFile.");
				return false;
			}

			int major = version.Major;
			int minor = version.Minor;
			int build = version.Build;
			int revision = version.Revision;
			var increment = false;
			if (this.IncrementMajor != null && bool.TryParse(this.IncrementMajor.ItemSpec, out increment) && increment)
				major++;
			if (this.IncrementMinor != null && bool.TryParse(this.IncrementMinor.ItemSpec, out increment) && increment)
				minor++;
			if (this.IncrementBuild != null && bool.TryParse(this.IncrementBuild.ItemSpec, out increment) && increment)
				build++;
			if (this.IncrementRevision != null && bool.TryParse(this.IncrementRevision.ItemSpec, out increment) && increment)
				revision++;

			var newVersion = new Version(major, minor, build, revision);
			if (version.CompareTo(newVersion) != 0)
			{
				versionString = newVersion.ToString();
				File.WriteAllText(versionFileName, versionString, Encoding.UTF8);
			}

			this.Value = new TaskItem(versionString);
			return true;
		}
	}
}
